package com.leyou.item.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.mapper.SpecParamMapper;
import com.leyou.item.pojo.SpecGroup;
import com.leyou.item.pojo.SpecParam;
import com.leyou.item.service.port.ISpecService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecService implements ISpecService {

    @Autowired
    private SpecGroupMapper specGroupMapper;

    @Autowired
    private SpecParamMapper specParamMapper;

    @Override
    public List<SpecGroupDTO> queryGroupByCategory(Long cid) {
        // 查询规格组
        SpecGroup record = new SpecGroup();
        record.setCid(cid);
        List<SpecGroup> specGroup = specGroupMapper.select(record);
        if (CollectionUtils.isEmpty(specGroup)) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        // 对象转换
        return BeanHelper.copyWithCollection(specGroup, SpecGroupDTO.class);
    }

    @Override
    public List<SpecParamDTO> querySpecParams(Long gid,Long cid,Boolean searching) {
        SpecParam record = new SpecParam();
        record.setGroupId(gid);
        record.setCid(cid);
        record.setSearching(searching);
        List<SpecParam> specParams = specParamMapper.select(record);
        if (CollectionUtils.isEmpty(specParams)) {
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(specParams, SpecParamDTO.class);
    }

    @Override
    @Transactional
    public void addGroup(SpecGroupDTO specGroupDTO) {
        SpecGroup specGroup = BeanHelper.copyProperties(specGroupDTO, SpecGroup.class);

        specGroupMapper.insertSelective(specGroup);
        System.out.println("service "+specGroup);
    }

    @Override
    public List<SpecGroupDTO> querySpecsByCid(Long id) {
        // 查询规格组
        List<SpecGroupDTO> groupList = queryGroupByCategory(id);
        // 查询分类下所有规格参数
        List<SpecParamDTO> params = querySpecParams(null, id, null);
        // 将规格参数按照groupId进行分组，得到每个group下的param的集合
        Map<Long, List<SpecParamDTO>> paramMap = params.stream()
                .collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        // 填写到group中
        for (SpecGroupDTO groupDTO : groupList) {
            groupDTO.setParams(paramMap.get(groupDTO.getId()));
        }
        return groupList;
    }
}
